package com.msl.debezium.common;

import com.msl.debezium.conf.Swagger2Conf;
import com.msl.debezium.jdbc.DataSourceContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyspaceEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Nullable;

@Component
public class RedisDbKeyListener extends KeyspaceEventMessageListener {

    private final Logger logger = LoggerFactory.getLogger(RedisDbKeyListener.class);

    @Autowired
    private Swagger2Conf swagger2Conf;

    @Autowired
    private RedisUtil redis;

    @Autowired
    private RedisMessageListenerContainer redisMessageListenerContainer;

    public RedisDbKeyListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void init() {
        super.doRegister(redisMessageListenerContainer);
    }

    @Override
    public void onMessage(Message message, @Nullable byte[] pattern){
        logger.info("onMessage start");
        if(message == null || ObjectUtils.isEmpty(message.getChannel()) || ObjectUtils.isEmpty(message.getBody())){
            return;
        }
        doHandleMessage(message);
    }


    @Override
    protected void doHandleMessage(Message message) {
        try {
            String key = message.toString();
            if("debe_db_datasource".equals(key)){
                this.changeDb();
            }
        } catch (Exception e){
            logger.error("ChangeDb occur an Exception");
        }
    }

    public void changeDb() throws Exception{
        try {
            String dbDatasource = redis.get("debe_db_datasource").toString();
            logger.info(this.getClass().getName()+",changeDb start,dbDatasource type is:" + dbDatasource);
            boolean flag = !DataSourceContextHolder.getDataSourceType().equals(dbDatasource);
            if("VM".equals(dbDatasource) || "WIN".equals(dbDatasource)){
                DataSourceContextHolder.setDataSourceType(dbDatasource);
                String podName = swagger2Conf.getLocalName();
                redis.sSet("debe_db_pod",podName);
                if(flag){
                    swagger2Conf.changeDocket(podName, dbDatasource);
                }
            }
            logger.info("changeDb end");
        }catch (Exception e){
            logger.error("changeDb error",e);
            throw new BizException("changeDb error");
        }
    }




}
